#include <QLibrary>
#include "ianimal.h"

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::LoadAndAction(QString strPluginName){
    // 加载插件dll
        QLibrary lib(strPluginName);
        if (lib.load())
        {
            // 定义插件中的两个导出函数的原型
            typedef IAnimal* (*CreateAnimalFunction)();
            typedef void (*ReleaseAnimalFunction)(IAnimal* animal);

            // 解析导出函数
            CreateAnimalFunction createAnimal =
                    (CreateAnimalFunction) lib.resolve("CreateAnimal");
            ReleaseAnimalFunction releaseAnimal =
                    (ReleaseAnimalFunction) lib.resolve("ReleaseAnimal");

            if (createAnimal && releaseAnimal)
            {
                // 创建Animal对象
                IAnimal * animal = createAnimal();
                if (animal)
                {
                    // 使用插件功能
                    animal->Eat();
                    animal->Sleep();
                    // 插件使用完毕，删除对象
                    releaseAnimal(animal);
                }
            }
            // 卸载插件
            lib.unload();
        }
}

void MainWindow::on_btnLoadAndAction_clicked()
{
    LoadAndAction(ui->cmbLib->itemText(0));
}
